package cn.tedu.vue_master.controller;

import cn.tedu.vue_master.exception.ACServiceException;
import cn.tedu.vue_master.restful.JsonResult;
import cn.tedu.vue_master.restful.ServiceCode;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/restTemplate")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class RestTemplateController {

    @Value("${vue_master.username}")
    private String username;
    @Value("${vue_master.password}")
    private String password;

    private final RestTemplate restTemplate;

    @GetMapping("/test")
    public JsonResult<String> test(HttpServletRequest request) {

        // 1、先访问本地/oauth/token获取accessToken
        // demo中也配置了，也可以进行访问
        String tokenUrl = "http://localhost:9080/oauth/token?client_id=4099c23e45f64c158065e1b062492357&client_secret=f5b351eb6df8458382d0303aae8a72d7275a2296ff45488c9f135ca120edebd1&grant_type=client_credentials";
        String accessToken = "";
        try {
            // 设置httpHeaders
            HttpHeaders headers = new HttpHeaders();
            // 添加参数
            HashMap<String, Object> paramMap = new HashMap<>();
            Map<String, String[]> parameterMap = request.getParameterMap();
            paramMap.put("client_id", parameterMap.get("client_id"));
            paramMap.put("client_secret", parameterMap.get("client_secret"));
            paramMap.put("grant_type", parameterMap.get("grant_type"));
            // 设置HttpEntity
            HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
            // 发送请求
//            ResponseEntity<String> response = restTemplate.exchange(tokenUrl,
//                    HttpMethod.GET,
//                    httpEntity,
//                    String.class);
//            String jsonString = response.getBody();
//            log.debug("jsonString = {}", jsonString);
//            JSONObject jsonObject = JSONObject.parseObject(jsonString);
//            String accessToken = String.valueOf(jsonObject.getObject("access_token", String.class));
//            return JsonResult.ok("获取accessToken成功:" + accessToken);
            String jsonString = restTemplate.getForObject(tokenUrl, String.class);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            accessToken = String.valueOf(jsonObject.getObject("access_token", String.class));
            return JsonResult.ok(accessToken);
        } catch (Exception e) {
            log.error("调用【{}】接口失败，错误信息：{}", tokenUrl, e);
            throw new ACServiceException(ServiceCode.ERR_BAD_REQUEST,e.getMessage());
        }

        // 2、携带accessToken，访问第三方接口，请求资源
        /*String url = "http://localhost:10003/api/test";
        try {
            HttpHeaders headers = new HttpHeaders();
            // 获取sso认证信息
            String authorization = request.getHeader("Authorization");
            // 放入header中
            headers.set("Authorization", authorization);
            MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
            messageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON,MediaType.APPLICATION_OCTET_STREAM));
            restTemplate.getMessageConverters().add(messageConverter);
            // 设置编码格式
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);

            // 添加参数
            MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
            Map<String, String[]> parameterMap = request.getParameterMap();
            paramMap.add("client_id", parameterMap.get("client_id"));
            paramMap.add("client_secret", parameterMap.get("client_secret"));
            paramMap.add("grant_type", parameterMap.get("grant_type"));

            // 设置HttpEntity
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap,headers);
            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(url,
                    HttpMethod.GET,
                    httpEntity,
                    String.class);
            return JsonResult.ok(response.getBody());
        } catch (Exception e) {
            log.error("调用【{}】接口失败，错误信息：{}", url, e);
            throw new ACServiceException(ServiceCode.ERR_BAD_REQUEST,e.getMessage());
        }*/

    }
}

